from Login import models
from django.utils import timezone
import datetime


# 隐藏用户的一些信息
class UserData:
    def __init__(self, user: dict):
        self.user = user

    def returnData(self):
        self.user.pop("user_id")
        self.user.pop("password")

        return self.user


# 用户注册
def userRegister(user_name, password, phone, email, code, address=''):
    samePhoneUser = models.User.objects.filter(phone=phone)
    same_userName_user = models.User.objects.filter(user_name=user_name)
    sameEmail = models.User.objects.filter(email=email)

    if same_userName_user:
        return {"msg": "该用户名已存在"}
    if sameEmail:
        return {"msg": "该邮箱已经被注册"}
    if samePhoneUser:
        return {"msg": "该电话号码已被注册"}

    # code_ = models.Code.objects.filter(user_email=email, status=1).first()
    code_ = models.Code.objects.filter(user_email=email, status=1).order_by("-create_time").first()
    if code_:
        latestCode = code_.code
        create_time = code_.create_time
        nowTime = timezone.now()

        if code is None:
            return {"msg": "请输入验证码"}
        if nowTime > create_time + datetime.timedelta(minutes=5):
            return {"msg": "该验证码已经过期"}
        if str(code) != latestCode:
            return {"msg": "验证码不正确"}

        user = models.User(user_name=user_name, password=password, phone=phone, email=email, address=address)

        # 注册完毕，将验证码状态设为失效
        user.save()
        makeCodeBeInvalid(email=email)
        return {"msg": "注册成功"}

    else:
        return {"msg": "请先点击发送验证码"}


# 用户登录
def userLogin(phone, password):
    if phone is None:                 # 12.29报错AttributeError: 'str' object has no attribute 'get'
        return {"msg": "请输入手机号"}  # 故全部将返回的值改成字典形式，原来返回的形式是字符串(主要是因为get取值只能从字典里面取)
    if password is None:
        return {"msg": "请输入密码"}

    user = models.User.objects.filter(phone=phone, password=password).values().first()
    if user:
        # 隐藏用户的一些信息
        userData = UserData(user=user).returnData()
        # print(userData)
        return {"msg": "登录成功", "data": userData}
    else:
        return {"msg": "手机号或者密码错误"}


# 将验证码状态设为失效
def makeCodeBeInvalid(email):
    code = models.Code.objects.filter(user_email=email).order_by('-create_time').first()
    if code:
        code.status = 0
        code.save()
    else:
        return {"msg": "验证码不存在"}


# 设置session
def setSession(request, phone, password):
    """设置session"""
    user = models.User.objects.filter(phone=phone, password=password).first()
    userId = user.user_id
    userName = user.user_name
    email = user.email

    request.session["isLogin"] = True
    request.session["userId"] = userId
    request.session["userName"] = userName
    request.session["email"] = email

    if not request.session.session_key:
        request.session.save()  # 如果没有则将session保存到数据库中
    sessionId = request.session.session_key  # 获取sessionId

    return sessionId


# 获取session正确后返回返回用户信息
def getSessionReturnUserData(request):
    userId = request.session.get("userId")

    user = models.User.objects.filter(user_id=userId).values().first()
    # 隐藏用户的一些信息
    userData = UserData(user=user).returnData()
    # 返回用户信息
    return userData


def getSessionReturnUserData1(sessionData):
    userId = sessionData.get("userId")

    user = models.User.objects.filter(user_id=userId).values().first()
    # 隐藏用户的一些信息
    userData = UserData(user=user).returnData()
    # 返回用户信息
    return userData
